import 'package:apple/model/DemoModel.dart';
import 'package:flutter/material.dart';
import 'package:yaml/yaml.dart';
import 'dart:convert';

import 'dart:async' show Future;
import 'package:flutter/services.dart' show rootBundle;




void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {

    return MaterialApp(
      title: 'Welcome to Flutter',
      home:  RandomWords(),
      theme: ThemeData(
        primaryColor: Colors.green,
      ),
    );
  }
}

class RandomWords extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return RandomWordsState();
  }
}

class RandomWordsState extends State<RandomWords> {

  final _biggerFont = const TextStyle(fontSize: 18.0);

  DemoModel _doc;

  @override
  void initState() {
    super.initState();

    loadAsset().then((V){
      print("yaml:"+V);

      YamlMap dict = loadYaml(V);
      String jsonString = json.encode(dict);
      Map map = json.decode(jsonString);

      print("2:" + jsonString);
      var demo = new DemoModel.fromJson(map);
      
      setState(() {
        _doc = demo;
      });
    });
  }

  Future<String> loadAsset() async {
    try {
      return await rootBundle.loadString('resource/route.yaml');
    } catch (e) {
      print(e);
      return '';
    }
  }

  @override
  Widget build(BuildContext context) {
    var title = json.encode(_doc);
    print('配置文件：'+title);
    // '$_counter'
    return new Scaffold (
      appBar: new AppBar(
        title: new Text('Widget'),
        actions: <Widget>[],
      ),
      body: _buildSuggestions(),
    );
  }

  Widget _buildSuggestions() {

    final tiles = _doc.root.map(
          (category) {
            return ListTile(
              title: Text(category.name, style: _biggerFont,),
              onTap: () {
                _pushSaved(category);
              },
            );
          }
        );

    final divided = ListTile.divideTiles(tiles: tiles, context: context).toList();
    return ListView(children: divided,);
  }

  void _pushSaved(CategoryModel category) {
    Navigator.of(context).push(
      MaterialPageRoute(builder: (context) {
        final tiles = category.children.map(
          (pair) {
            return ListTile(
              title: Text(pair.name, style: _biggerFont,),
            );
          }
        );

        final divided = ListTile.divideTiles(tiles: tiles, context: context).toList();

        return Scaffold(
          appBar: AppBar(
            title: Text(category.name),
          ),
          body: ListView(children: divided,),
        );
      })
    );
  }
}

